const http = require("https");
const cheerio = require("cheerio");
const fs = require("fs")
const loadImg = require("./loadImg")

// let resContext;
// http://goss.cfp.cn/static/home/v2_1.png
// const url = "https://car.autohome.com.cn/pic/series/3154-1.html#pvareaid=2042222";
const url = "https://club.autohome.com.cn/bbs/thread/4669a79e52ce2bec/85506107-1.html";
http.get(url,(res)=>{
    const { statusCode } = res;
    const contentType = res.headers['content-type'];

    let error
    // console.log(statusCode)
    // if(statusCode !== 200){
    //     error = new Error("请求失败")
    // }
    // if(error){
    //     console.log(error)
    //     //  消费响应数据来释放内存
    //     res.resume();
    //     return ;
    // }
    res.setEncoding("utf8");

    let resContext = "";
    // let i=0;
    res.on("data",(chunk)=>{
        // console.log("分段响应"+ (i++));
        resContext += chunk;
    })
    res.on("end",()=>{
        // console.log("end")
        const $ = cheerio.load(resContext);
        let imgList = [];
        let str = "";
        $("img").each((index,item)=>{
            str = $(item).attr("src");
            // console.log($(item).attr("src"))
            // if( !str || str.indexOf("lazyload") == -1){
            //     str = $(item).attr("src9");
                // console.log("src9:"+$(item))
            // }
            if( typeof str === "string" && str.indexOf('lazyload') !== -1 && $(item).attr("src9")){ // 
                str = $(item).attr("src9")
            }
            if(str && str != undefined && str != "undefined" ){
                imgList.push(str);
            }
        })
        console.log(imgList.join("\n"));
        // console.log(imgList);
        // console.log(imgList);
        // return 
        // fs.unlink("./bilibili.html",(err)=>{})
        // fs.writeFileSync("./bilibili.html",imgList.join("\n"));
        let path = "";
        imgList.forEach((item,index)=>{
            path = "./img/"+index+".jpg";
            loadImg("https:"+item,path);
        })
    })
}).on("error",(err)=>{
    console.log(err);
});